//
//  MXNetEngine.m
//  MXApp
//
//  Created by ChenChao on 15/1/15.
//  Copyright (c) 2015年 YingXiang. All rights reserved.
//

#import "NetWorkEngine.h"
#import "RequestConstants.h"
#import "SFHFKeychainUtils.h"
#import "UserManager.h"
#import "AppDelegate.h"

// UdidKeyChainParam
#define K_KeyChainAppID @"AppDeviceIdentifier"
#define K_KeyChainAppGroup @"com.CC.AppIdentifier"

@implementation NetWorkEngine
+ (instancetype)sharedEngine {
  static NetWorkEngine* s_sharedEngine = nil;
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    s_sharedEngine = [[[self class] alloc] initWithBaseURL:[NSURL URLWithString:APP_URISCHEME]];
  });
  NSString* session = [[UserManager sharedInstance] clientToken];
  if (session.length > 0) {
    [s_sharedEngine.requestSerializer setValue:session forHTTPHeaderField:REQUEST_HEADER_SESSIONID];
  } else {
    [s_sharedEngine.requestSerializer setValue:@"" forHTTPHeaderField:REQUEST_HEADER_SESSIONID];
  }
  return s_sharedEngine;
}

- (instancetype)initWithBaseURL:(NSURL*)url
           sessionConfiguration:(NSURLSessionConfiguration*)configuration {
  self = [super initWithBaseURL:url sessionConfiguration:configuration];
  if (self) {
    [self.requestSerializer setValue:[NetWorkEngine screenScale]
                  forHTTPHeaderField:REQUEST_HEADER_SCREEN];
    [self.requestSerializer setValue:[NetWorkEngine clientPlatform]
                  forHTTPHeaderField:REQUEST_HEADER_PLATFORM];
    [self.requestSerializer setValue:[NetWorkEngine clientUdid]
                  forHTTPHeaderField:REQUEST_HEADER_UDID];
    [self.requestSerializer setValue:[NetWorkEngine clientVersion]
                  forHTTPHeaderField:REQUEST_HEADER_VERSION];
    self.responseSerializer.acceptableContentTypes =
        [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html",
                              @"text/plain", @"", nil];
    self.requestSerializer.stringEncoding = NSUTF8StringEncoding;
    _requestGroup = [[NetWorkRequestGroup alloc] init];
  }
  return self;
}

- (NSURLSessionDataTask*)POST:(NSString*)URLString
                   parameters:(id)parameters
                     progress:(void (^)(NSProgress* _Nonnull))uploadProgress
                      success:(void (^)(NSURLSessionDataTask* _Nonnull, id _Nullable))success
                      failure:
                          (void (^)(NSURLSessionDataTask* _Nullable, NSError* _Nonnull))failure {
  return [self POST:URLString
         parameters:parameters
            headers:@{}
           progress:uploadProgress
            success:success
            failure:failure];
}

- (NSURLSessionDataTask*)POST:(NSString*)URLString
                   parameters:(id)parameters
    constructingBodyWithBlock:(void (^)(id<AFMultipartFormData> _Nonnull))block
                     progress:(void (^)(NSProgress* _Nonnull))uploadProgress
                      success:(void (^)(NSURLSessionDataTask* _Nonnull, id _Nullable))success
                      failure:
                          (void (^)(NSURLSessionDataTask* _Nullable, NSError* _Nonnull))failure {
  return [self POST:URLString
                     parameters:parameters
                        headers:@{}
      constructingBodyWithBlock:block
                       progress:uploadProgress
                        success:success
                        failure:failure];
}

- (NSURLSessionDataTask*)GET:(NSString*)URLString
                  parameters:(id)parameters
                    progress:(void (^)(NSProgress* _Nonnull))downloadProgress
                     success:(void (^)(NSURLSessionDataTask* _Nonnull, id _Nullable))success
                     failure:(void (^)(NSURLSessionDataTask* _Nullable, NSError* _Nonnull))failure {
  return [self GET:URLString
        parameters:parameters
           headers:@{}
          progress:downloadProgress
           success:success
           failure:failure];
}

+ (NSString*)stringWithUUID {
  CFUUIDRef uuidObj = CFUUIDCreate(nil);
  NSString* uuidString = (__bridge_transfer NSString*)CFUUIDCreateString(nil, uuidObj);
  return uuidString;
}

+ (NSString*)getKeyChainOfValue {
  NSError* error = nil;
  NSString* deviceKey = [SFHFKeychainUtils getPasswordForUsernameOld:K_KeyChainAppID
                                                      andServiceName:K_KeyChainAppGroup
                                                               error:&error];
  if (!(deviceKey.length == 0)) {
    deviceKey = [self stringWithUUID];
    [SFHFKeychainUtils storeUsername:K_KeyChainAppID
                         andPassword:deviceKey
                      forServiceName:K_KeyChainAppGroup
                      updateExisting:NO
                               error:&error];
  }
  return deviceKey;
}

+ (NSString*)screenScale {
  return [NSString stringWithFormat:@"%.0fx%.0f", [UIScreen mainScreen].bounds.size.width,
                                    [UIScreen mainScreen].bounds.size.height];
}

+ (NSString*)clientPlatform {
  return @"iOS";
}

+ (NSString*)clientUdid {
  return [self getKeyChainOfValue];
}

+ (NSString*)clientVersion {
  NSString* version =
      [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString*)kCFBundleVersionKey];
  return version;
}

@end
